﻿Ext.define("GS.controller.Comment", {
    extend: "Ext.app.Controller",

    config: {
        refs: {
            mainView: "main",
            viewPost: "viewpost",
            commentView: "addcomment",
            CommentForm: '#commentform',
            btnBackViewPost: "#btnBackViewPost",
            btnSubmitComment: "#btnSubmitComment",
            btnCancelComment: "#btnCancelComment"
        },
        control: {
            btnBackViewPost: {
                tap: "onBackViewPost"
            },
            btnSubmitComment: {
                tap: "onSubmitComment"
            },
            btnCancelComment: {
                tap: "onCancelComment"
            }
        }
    },
    onBackViewPost: function () {
        Ext.Viewport.setActiveItem(this.getMainView());
    },
    onCancelComment: function (id) {
        Ext.getCmp('commentlist').getStore().load();
        Ext.Viewport.setActiveItem(this.getViewPost());
    },
    onSubmitComment: function () {
        var values = this.getCommentForm().getValues();
        var now = new Date();

        var user = Ext.create('GS.store.UserData');

        user.load();

        var user_id = user.getAt(0).get('user_id');

        var model = Ext.create('GS.model.comment.Comment', values);
                                
        var errors = model.validate();
        if(errors.isValid()){
            Ext.data.JsonP.request({
                url: GS.util.Config.getServerUrl() + 'AddComment.php',
                callbackKey: "callback",
                params: { post_id: values.post_id, user_id: user_id, body: values.body, date_posted: now},

                success: function (response) {
                    var text = response.responseText;
                    Ext.Msg.alert('Success', text);
                },

                failure: function (response) {
                    Ext.Msg.alert('Error', 'Error while submitting the form');
                }
            });

            Ext.getCmp('commentlist').getStore().load();
            Ext.Viewport.setActiveItem(this.getViewPost());
        } else {
            var errorMessage = "";
            Ext.each(errors.items, function (rec, i) {
                errorMessage += rec.config.message + "<br/>";
            });
            Ext.Msg.alert("Fejl", errorMessage, function () { });
            return false;
        }
    }
});